<template>
  <el-dialog :title="title" v-model.visible="dialogVisible" width="600px"
    class="importWorkflowFileDialog dialog-vertical-center dialog-body-padding-top-bottom-0" append-to-body
    :close-on-click-modal="false" :close-on-press-escape="false" @close="dialogClose" @closed="dialogClose">
    <div class="flowConfigForm">
      <el-upload v-if="cellsLength === -1" ref="elUploadRef" class="upload-demo" drag action="" :accept="accept"
        :auto-upload="false" :on-change="uploadChange">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__text">只能上传工作流导出ZIP文件</div>
      </el-upload>
      <div v-else class="uploadFile">
        <p>文件名称: {{ uploadFileName }}</p>
        <p>画布算子数量: {{ cellsLength }}</p>
        <el-button type="text" @click="uploadDataInit()">重新选择文件</el-button>
      </div>
    </div>
    <template #footer>
      <div>
        <el-button @click="dialogClose()">取消</el-button>
        <el-button type="primary" :loading="btnSaveLoading" @click="saveCommit">{{ buttonText }}</el-button>
      </div>
    </template>
    <save-version-dialog v-if="saveVersionDialogVisible" ref="saveVersionDialog" v-model="saveVersionDialogVisible"
      @successFunc="versionSaveSuccess()" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue"
import { designerStore } from 'src/stores/designerTool/designerTool'
import JSZip from 'jszip'
import { base64ToBlob, blobToFile } from 'src/utils/designerTool/toole'
import EncryptionDecryption from 'src/utils/designerTool/EncryptionDecryption'
import SaveVersionDialog from './saveVersionDialog.vue'
import { isObject } from 'src/utils/designerTool/validate'
import dagGraph from 'src/pages/designerTool/canvas/DagEdit/graph/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
const router = useRouter()
const store = designerStore()
const dialogVisible = ref(false)
const buttonText = ref('确定')
const title = ref('导入工作流文件')
const btnSaveLoading = ref(false)
const cellsLength = ref(-1)
const accept = ref('.zip')
const uploadFileName = ref('')
const dagData = ref(null)
const iconFile = ref(null)
const saveVersionDialogVisible = ref(false)
const versionSaveSuccessState = ref(false)
const saveVersionDialog = ref(null)
const elUploadRef = ref(null)

function init() {
  dialogVisible.value = true
}
const emits = defineEmits(['dialogClose', 'fileData'])
function dialogClose() {
  emits('dialogClose')

}
function versionSaveSuccess() {
  versionSaveSuccessState.value = true
  saveCommit()
}

function saveCommit() {
  if (uploadFileName.value) {
    if (dagData.value.cells.length) {
      if (router.currentRoute.value.name == 'designer-tool') {
        emits('fileData', [iconFile.value,dagData.value,uploadFileName.value])
        dialogClose()
      } else {
        saveData()
      }
    }
  } else {
    ElMessage('请选择一个文件')
  }
}
function saveData() {
  btnSaveLoading.value = true
  dagGraph.saveImportWorkflowData(iconFile.value, dagData.value).then(res => {
    ElMessage.success('导入数据保存成功')
    store.SET_PUBLISH_EVENT({
      key: 'resetEvent',
      data: 'init'
    })
    dialogClose()
  }, error => {
    ElMessage.error('导入数据保存失败:' + error.result)
  }).finally(() => {
    btnSaveLoading.value = false
  })
}
function uploadChange(file: any) {
  const keyList = ['default', 'framework', 'runtime', 'section']
  uploadDataInit()
  if (file.size) {
    const zipFile = file.raw
    const jszip = new JSZip()
    jszip.loadAsync(zipFile).then((zip) => { // 读取zip
      for (const key in zip.files) { // 判断是否是目录
        if (!zip.files[key].dir) {
          if (key === 'image.png') {
            zip.file(zip.files[key].name).async('base64').then((res) => {
              const blob = base64ToBlob(`data:image/png;base64,${res}`)
              const file = blobToFile(blob, 'icon.png')
              iconFile.value = file
            })
          } else if (/\.(workflow)$/.test(zip.files[key].name)) {
            zip.file(zip.files[key].name).async(
              'string').then(res => {
                try {
                  const uploadData = EncryptionDecryption.Decrypt(res)
                  if (isObject(uploadData)) {
                    if (uploadData.dag && uploadData.dag.cells && Array.isArray(uploadData.dag.cells)) {
                      // 对输入算子做内容清空处理
                      // try {
                      //   uploadData.dag.cells.forEach((row:any) => {
                      //     if (row.data && store.dataReadIdList.includes(row.data.id) && row.data.configs) {
                      //       keyList.forEach(rowKey => {
                      //         row.data.configs[rowKey].forEach((configRow:any) => {
                      //           configRow.value = null
                      //         })
                      //       })
                      //     }
                      //   })
                      // } catch (e) {
                      //   console.error(e)
                      // }
                      cellsLength.value = uploadData.dag.cells.filter((item: any) => item.shape === 'vue-shape' && item.component === 'algo-node').length
                      dagData.value = uploadData.dag
                      uploadFileName.value = file.name
                    }
                  } else {
                    uploadFileError()
                  }
                } catch (e) {
                  uploadFileError()
                }
              })
          }
        }
      }
    })
  }
}
function uploadDataInit() {
  if (btnSaveLoading.value) {
    ElMessage.warning('正在导入中...,请稍等.')
  } else {
    uploadFileName.value = ''
    cellsLength.value = -1
    dagData.value = null
    iconFile.value = null
  }
}
function uploadFileError() {
  ElMessage.error('导入文件错误,请检查文件是否为正确的工作流导出文件.')
  UploadRef.value?.clearFiles()
}
defineExpose({ init })
</script>

<style lang="scss" scoped>
.importWorkflowFileDialog {
  .flowConfigForm {
    .upload-demo {
      ::v-deep .el-upload {
        width: 100%;

        .el-upload-dragger {
          width: 100%;
          height: 210px;
          line-height: 2;
        }
      }
    }
  }
}
</style>
